package com.example.petplanet.intercept;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.example.petplanet.domain.User;
import com.example.petplanet.util.JWTUtil;
import com.example.petplanet.util.SecureEncryptionUtil;
import com.example.petplanet.util.TLUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class TokenIntercept implements HandlerInterceptor {

    @Value("${app.jwt_secret}")
    private String secret;

    @Value("${app.appid}")
    private String appid;

    @Value("${app.secret}")
    private String appSecret;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //这里request和response都是引用对象
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token=request.getHeader("Authorization");

        response.setContentType("application/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");

        if (token == null || token.isEmpty()) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("Token missing");
            return false;
        }
        //验证token
        String userIdentity = JWTUtil.checkToken(token, response, secret);
        if (StrUtil.isBlank(userIdentity)) return false;
        String userIdStr = SecureEncryptionUtil.decrypt(userIdentity, appid, appSecret);
        //通过redis查看用户是否已登录
        String key="app:user:"+userIdStr;
        Map<Object,Object> userMap=stringRedisTemplate.opsForHash().entries(key);
        String redisToken = (String) userMap.get("token");
        String userJson= (String) userMap.get("user");
        User user = JSON.parseObject(userJson, User.class);
        if(redisToken ==null || user ==null){
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            response.getWriter().write("还未登录");
            return false;
        }
        if(!redisToken.equals(token.substring(7))){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("该账号已在另一台设备登录");
            return false;
        }
        //存储user_id到TL中(后续处理异常）
        long userId = Long.parseLong(userIdStr);
        TLUtil.setUserId(userId);
        TLUtil.setUser(user);
        stringRedisTemplate.expire(key,10,TimeUnit.DAYS);
        return true;
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        TLUtil.removeUserId();
        TLUtil.removeUser();
    }
}
